package admin

import (
	"go-weiqi-system/config"
	"go-weiqi-system/internal/models"
	"go-weiqi-system/internal/utils"

	"github.com/gin-gonic/gin"
)

type AppointmentTimeController struct{}

// Index 约棋时间段列表
func (ctrl *AppointmentTimeController) Index(c *gin.Context) {
	var param models.PageParam
	if err := c.ShouldBindQuery(&param); err != nil {
		param.Page = 1
		param.PageSize = 10
	}

	var timeSlots []models.AppointmentTime
	var total int64

	db := config.DB.Model(&models.AppointmentTime{})

	db.Count(&total)
	db.Order("sort desc, id desc").
		Offset(param.GetOffset()).
		Limit(param.GetPageSize()).
		Find(&timeSlots)

	utils.Success(c, models.PageResponse{
		List:     timeSlots,
		Total:    total,
		Page:     param.GetPage(),
		PageSize: param.GetPageSize(),
	})
}

// Add 添加约棋时间段
func (ctrl *AppointmentTimeController) Add(c *gin.Context) {
	var timeSlot models.AppointmentTime
	if err := c.ShouldBindJSON(&timeSlot); err != nil {
		utils.Error(c, "参数错误")
		return
	}

	if err := config.DB.Create(&timeSlot).Error; err != nil {
		utils.Error(c, "添加失败")
		return
	}

	utils.Success(c, timeSlot, "添加成功")
}

// Edit 编辑约棋时间段
func (ctrl *AppointmentTimeController) Edit(c *gin.Context) {
	var req struct {
		ID uint `json:"id" binding:"required"`
		models.AppointmentTime
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		utils.Error(c, "参数错误")
		return
	}

	var timeSlot models.AppointmentTime
	if err := config.DB.First(&timeSlot, req.ID).Error; err != nil {
		utils.Error(c, "时间段不存在")
		return
	}

	req.AppointmentTime.ID = req.ID
	if err := config.DB.Save(&req.AppointmentTime).Error; err != nil {
		utils.Error(c, "更新失败")
		return
	}

	utils.Success(c, req.AppointmentTime, "更新成功")
}

// Delete 删除约棋时间段
func (ctrl *AppointmentTimeController) Delete(c *gin.Context) {
	var req struct {
		ID uint `json:"id" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		utils.Error(c, "参数错误")
		return
	}

	if err := config.DB.Delete(&models.AppointmentTime{}, req.ID).Error; err != nil {
		utils.Error(c, "删除失败")
		return
	}

	utils.Success(c, nil, "删除成功")
}
